﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using QuanLyGiaoVuDAL.ADOWrapper;
using QuanLyGiaoVuDAL.Mapper;
using QuanLyGiaoVuDAL.DTO;
using System.Data.SqlClient;
using System.Data;

namespace QuanLyGiaoVuDAL.Repositories.DatabaseRepositories
{
    public class NguoiDungRepository:INguoiDungRepository
    {
        public NguoiDungDTO DangNhapNguoiDung(NguoiDungDTO nguoiDungDTO)
        {
            var dbResult = StoreProcedureExecutor.ExecuteStoreProcedure("[dbo].[usp_DANGNHAP_NGUOIDUNG]", GetParameterArray(nguoiDungDTO));
            try
            {
                var dataRow = dbResult.Tables[0].Rows[0];
                return dataRow.ToNguoiDungDTO();
            }
            catch (Exception ex)
            {
                return null;
            }            
        }        
        public NguoiDungDTO DoiMatKhauNguoiDung(NguoiDungDTO nguoiDungDTO)
        {
            var dbResult = StoreProcedureExecutor.ExecuteStoreProcedure("[dbo].[usp_DOIMATKHAU_NGUOIDUNG]", GetParameterArray(nguoiDungDTO));
            try
            {
                var dataRow = dbResult.Tables[0].Rows[0];
                return dataRow.ToNguoiDungDTO();
            }
            catch (Exception ex)
            {
                return null;
            }        
        }
        #region Private Methods
        private System.Data.SqlClient.SqlParameter[] GetParameterArray(NguoiDungDTO nguoiDungDTO)
        {
            SqlParameter[] parameters = new SqlParameter[5];
            parameters[0] = DBParameterFactory.Create("TaiKhoanDangNhap", nguoiDungDTO.TaiKhoanDangNhap);
            parameters[1] = DBParameterFactory.Create("MatKhau",nguoiDungDTO.MatKhau);            
            parameters[2] = DBParameterFactory.Create("MatKhauMoi", nguoiDungDTO.MatKhauMoi);
            parameters[3] = DBParameterFactory.Create("VaiTro", nguoiDungDTO.VaiTro);
            parameters[4] = DBParameterFactory.Create("isGiangVien", nguoiDungDTO.IsGiangVien);
            return parameters;
        }

        #endregion


        public NguoiDungDTO GetNguoiDungByTaiKhoan(string taiKhoan)
        {
            try
            {
                var taiKhoanParameter = DBParameterFactory.Create("TaiKhoanDangNhap", SqlDbType.VarChar, taiKhoan);
                var dbResult = StoreProcedureExecutor.ExecuteStoreProcedure("[dbo].[usp_NGUOIDUNGSelect]", taiKhoanParameter);
                var dataRow = dbResult.Tables[0].Rows[0];
                return dataRow.ToNguoiDungDTO();
            }
            catch
            {
                return null;
            }
        }
    }
}
